package org.millioncall.yueyoga.common.security;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.millioncall.openplatform.util.WebAppUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.access.AccessDeniedHandler;

public class ZhuwAccessDeniedHandler implements AccessDeniedHandler {
	protected static final Logger logger = LoggerFactory
			.getLogger(ZhuwAccessDeniedHandler.class);
	private String errorPage;
	private boolean enableAjaxRequestHandler = false;

	@Override
	public void handle(HttpServletRequest request,
			HttpServletResponse response,
			AccessDeniedException accessDeniedException) throws IOException,
			ServletException {
		if (!response.isCommitted()) {
			if (enableAjaxRequestHandler && WebAppUtils.isAjaxRequest(request)) {
				String msg = "{'success':false,'type':'forbidden','status':'403','msg':'对不起，您没有访问"
						+ request.getRequestURI() + "的权限，请联系管理员'}";
				WebAppUtils.ajaxResponse(response, msg);
			} else {
				if (errorPage != null) {
					request.setAttribute(WebAttributes.ACCESS_DENIED_403,
							accessDeniedException);
					response.setStatus(HttpServletResponse.SC_FORBIDDEN);
					RequestDispatcher dispatcher = request
							.getRequestDispatcher(errorPage);
					dispatcher.forward(request, response);
				} else {
					response.sendError(HttpServletResponse.SC_FORBIDDEN,
							accessDeniedException.getMessage());
				}
			}
		}
	}

	public void setErrorPage(String errorPage) {
		if ((errorPage != null) && !errorPage.startsWith("/")) {
			throw new IllegalArgumentException("errorPage must begin with '/'");
		}
		this.errorPage = errorPage;
	}

	public void setEnableAjaxRequestHandler(boolean enableAjaxRequestHandler) {
		this.enableAjaxRequestHandler = enableAjaxRequestHandler;
	}
}
